package cmd

import (
	"gitee.com/godY/daminghu-cli/common"
	"gitee.com/godY/daminghu-cli/handler"
)

var (
	beforeHandlers []interface{}
	serverHandlers []interface{}
	webHanders     []interface{}
	afterHandlers  []interface{}
)

func AddBeforeHandler(h interface{}) {
	beforeHandlers = append(beforeHandlers, h)
}

func AddAfterHandler(h interface{}) {
	afterHandlers = append(afterHandlers, h)
}

func AddServerHandler(h interface{}) {
	serverHandlers = append(serverHandlers, h)
}

func AddWebHandler(h interface{}) {
	webHanders = append(webHanders, h)
}

func handleOneTable(tables []*common.Table, handlers []interface{}) {
	for _, t := range tables {

		for _, sh := range handlers {

			switch sh.(type) {
			case handler.HandlerOneTableFunc:
				if fun, ok := sh.(handler.HandlerOneTableFunc); ok {
					fun(t, t.Columns)
				}
				break
			}
		}
	}
}

func handlerTables(tables []*common.Table, handlers []interface{}) {
	for _, sh := range handlers {

		switch sh.(type) {
		case handler.HandlerTablesFunc:
			if fun, ok := sh.(handler.HandlerTablesFunc); ok {
				fun(tables)
			}
			break
		}
	}
}

func Start(cmds []string, values []string) {

	CheckCmds(cmds, values)

	for index, cmd := range cmds {
		if cmdBeforeFunc, ok := CmdBeforeFuncMap[cmd]; ok {
			cmdBeforeFunc(values[index])
		}
		CmdFuncMap[cmd](values[index])
		if cmdAfterFunc, ok := CmdAfterFuncMap[cmd]; ok {
			cmdAfterFunc(values[index])
		}
	}
}
